

package com.walk.zworld.square.network

import com.google.gson.JsonSyntaxException
import com.base.lib.log.KLog
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 获取网络请求返回的异常信息。
 * @since  2020/5/29
 */
object ResponseHandler {

    private const val TAG = "ResponseHandler"

    /**
     * 当网络请求没有正常响应的时候，根据异常类型进行相应的处理。
     * @param e 异常实体类
     */
    fun getFailureTips(e: Throwable?): String {
        KLog.e(TAG, "getFailureTips exception is ${e?.message}")
        return when (e) {
            is ConnectException -> "网络连接异常"
            is SocketTimeoutException -> "网络连接超时"
            is ResponseCodeException -> "服务器状态码异常：" + e.responseCode
            is NoRouteToHostException -> "无法连接到服务器"
            is UnknownHostException -> "网络错误"
            is JsonSyntaxException -> "数据解析异常"
            else -> {
                "发生未知错误"
            }
        }
    }
}

class ResponseCodeException(val responseCode: Int) : RuntimeException("Http request failed with response code $responseCode")
